var api = require('../config/api.js');
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
// 获取当前页路径
function getCurrentPagePath(){
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  console.log("当前页路径" + currentPage)
  return url
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {

        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/auth/login/login'
            });
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}
// 定时器
function timer(that){
  let val = setInterval(function () {
    that.setData({
      codeTip: that.data.codeTip - 1
    })
    console.log(that.data.codeTip)
    if (that.data.codeTip == 0) {
      clearInterval(val)
    }
  }, 1000)
}
//时间倒计时
function timecutDown(that) {
  let currentTime = new Date().getTime() //当前时间毫秒数
  let endTimes = that.data.endTime //结束时间
  let totalSecond = endTimes - currentTime || 0
  // console.log('当前时间' + currentTime + '\n剩余时间：' + totalSecond + '\n结束时间：' + endTimes);
  if (totalSecond > 0) {
    let countTimes = formatTime(totalSecond)
    //渲染时钟
    that.setData({
      countDay: countTimes.totalDay,
      countHour: countTimes.totalHour,
      countMinute: countTimes.totalMinute,
      countSecond: countTimes.second,
      countTotalSecond: totalSecond
    })
    let val = setTimeout(() => {
      totalSecond -= 1000;
      timecutDown(that)
      if (totalSecond < 0) {
        clearTimeout(val)
        util.request(api.closeCountDown).then(res => {
          if (res.errno == 0) {
            that.setData({
              switchOff: false
            })
          }
        })
      }
    }, 1000)

  }
}
// 时间格式化
function formatTime(totalSeconds) {
  let totalSecond = Math.floor(totalSeconds / 1000) //总秒数
  let totalDay = Math.floor(totalSecond / 3600 / 24) //总天数
  let totalHour = Math.floor(totalSecond / 3600 % 24) //总时
  let totalMinute = Math.floor(totalSecond / 60 % 60) //总分
  let second = Math.floor(totalSecond % 60) //总秒
  return {
    totalDay,
    totalHour,
    totalMinute,
    second
  }
}
module.exports = {
  formatTime,
  request,
  redirect,
  showErrorToast,
  getCurrentPagePath,
  timer,
  timecutDown
}


